package com.example.zyl.common.query.aspect;

import com.example.zyl.common.utils.ClientIpUtil;
import com.example.zyl.common.utils.ServletUtils;
import com.example.zyl.common.utils.ToolUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
@Order(1)
public class TimerAspect {

    private final InheritableThreadLocal<StopWatch> inheritable = new InheritableThreadLocal<>();


    @Before(value = "execution(* com.example.zyl.api.controller..*.*(..))")
    public void before(JoinPoint joinPoint) throws Throwable {
        //获取请求
        HttpServletRequest request = ServletUtils.getRequest();
        if (null == request) {
            return;
        }
        //请求地址
        String url = request.getMethod() + " " + request.getRequestURI();
        //ip地址
        String clientIp = ClientIpUtil.getClientRealIp(request);
        String jsonParams = ToolUtils.argsArrayToString(joinPoint.getArgs());
        log.info("[LOG]开始请求 => URL[{}],请求IP[{}],参数类型[json],参数:[{}]", url, clientIp, jsonParams);

        StopWatch stopWatch = new StopWatch();
        inheritable.set(stopWatch);
        stopWatch.start();
    }



    @After(value = "execution(* com.example.zyl.api.controller..*.*(..))")
    public void after(JoinPoint joinPoint) throws Throwable {

        HttpServletRequest request = ServletUtils.getRequest();
        if (null == request) {
            return;
        }
        String clientIp = ClientIpUtil.getClientRealIp(request);
        StopWatch stopWatch = inheritable.get();
        stopWatch.stop();
        log.info("[LOG]结束请求 => URL[{}],请求IP[{}],耗时:[{}]毫秒", request.getMethod() + " " + request.getRequestURI(), clientIp, stopWatch.getTime());
        inheritable.remove();
    }






}
